package org.ftz.control;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class ImageThread implements Runnable { //屏幕截取器和发送器，这里需要拿到socket的out流
    DataOutputStream dos = null;    //数据输出流
    int sleepTime = 50;
    public ImageThread(DataOutputStream dos, int sleepTime) {
        this.dos = dos;
        this.sleepTime = sleepTime;
    }
    @Override
    public void run() {
        try {
            Robot robot = new Robot();
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); //截取整个屏幕
            Rectangle rec = new Rectangle(dimension);
            BufferedImage image;
            byte imageBytes[];
            while (true) {
                image = robot.createScreenCapture(rec);
                imageBytes = getImageBytes(image);
                dos.writeInt(imageBytes.length);
                dos.write(imageBytes);
                dos.flush();
                Thread.sleep(sleepTime);   //线程睡眠
            }
        } catch (AWTException | IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public byte[] getImageBytes(BufferedImage image) throws IOException {  //压缩图片
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", baos);
        return baos.toByteArray(); //转换成byte数组
    }
}
